package com.sendpo.zjx.sendpo.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.github.czy1121.view.CornerLabelView;
import com.gongwen.marqueen.MarqueeFactory;
import com.gongwen.marqueen.MarqueeView;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableScrollView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.ExpressHomeActivity;
import com.sendpo.zjx.sendpo.activity.FabuxingChengActivity;
import com.sendpo.zjx.sendpo.activity.GeneicStoreInfoActivity;
import com.sendpo.zjx.sendpo.activity.LoginActivity;
import com.sendpo.zjx.sendpo.activity.MyselfjijianActivity;
import com.sendpo.zjx.sendpo.domain.BibiliNvgDomain;
import com.sendpo.zjx.sendpo.domain.StoreDomain;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.sendpo.zjx.sendpo.views.AutoScrollViewPager;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by zjx on 2018
 */

public class WuliuMainFragment extends BaseMainFragment implements AMapLocationListener {
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.index_main_imgviewpager)
    AutoScrollViewPager indexMainImgviewpager;
    @BindView(R.id.storenoticehead_mv)
    MarqueeView storenoticeheadMv;
    @BindView(R.id.store_recycler)
    RecyclerView storeRecycler;
    @BindView(R.id.scrollView)
    PullableScrollView scrollView;

    private LinearLayoutManager lm;
    MerRecylcerAdaper adater;
    @BindView(value = R.id.pulltofresh)
    PullToRefreshLayout pulltofresh;
    private View rootView;
    public static final int[] imgs_dot = new int[]{R.id.dot1, R.id.dot2, R.id.dot3};
   public boolean isloading=false;
   public int pagenow=1;
    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_main_wuliu, null);
        ButterKnife.bind(view, mActivity);
        return view;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            ButterKnife.bind(this, rootView);
            System.out.println("****************getHoinitDatat:");
            initData();
        }


        return rootView;
    }

    private void initData() {
        lm = new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        storeRecycler.setLayoutManager(lm);
        pulltofresh.setPullUpEnable(false);
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                pagenow=1;
                AmapLocationService amapLocationService = new AmapLocationService(mActivity);
                amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
                amapLocationService.registerListener(WuliuMainFragment.this);
                amapLocationService.start();
                nvg();
                initHot();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
            }
        });
        indexMainImgviewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        indexMainImgviewpager.stopAutoScroll();
                        pulltofresh.setPullDownEnable(false);
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        pulltofresh.setPullDownEnable(false);
                        break;
                    case MotionEvent.ACTION_UP:
                        pulltofresh.setPullDownEnable(false);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        indexMainImgviewpager.startAutoScroll();
                        pulltofresh.setPullDownEnable(true);
                        break;
                }
                return false;
            }
        });



        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_MOVE:
                        int scrollY=view.getScrollY();
                        int height=view.getHeight();
                        int scrollViewMeasuredHeight=scrollView.getChildAt(0).getMeasuredHeight();
                        if(scrollY==0){
                            System.out.println("*******************滑动到了顶端 view.getScrollY()="+scrollY);
                        }
                        if((scrollY+height)==scrollViewMeasuredHeight){
                            if(adater!=null&&adater.dataBeen.size()>=10&&isloading==false){
                             pagenow++;
                                appendHot();

                            }

                        }
                        break;
                }
                return false;
            }
        });
        pagenow=1;
        AmapLocationService amapLocationService = new AmapLocationService(mActivity);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(WuliuMainFragment.this);
        amapLocationService.start();
        nvg();
        initHot();
    }


    @OnClick(value = {R.id.myselfjijian_bt, R.id.songbaojijian_bt, R.id.wantjiedan_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.myselfjijian_bt:
                List<User> userList = Xutils.queryAll(this.mActivity.getApplication(), User.class);
                if (userList == null || userList.size() == 0) {
                    Tools.redirectActivity(this.mActivity, LoginActivity.class);
                    return;
                }
                Tools.redirectActivity(this.mActivity, MyselfjijianActivity.class);
                break;

            case R.id.songbaojijian_bt:
                Tools.redirectActivity(this.mActivity, ExpressHomeActivity.class);
                break;
            case R.id.wantjiedan_bt:
                Tools.redirectActivity(mActivity, FabuxingChengActivity.class);
                break;
        }

    }

    //自营导航条
    public void nvg() {
        String cache_result = Tools.getCache(mActivity, HttpUrl.getBilling + "location:2");
        Gson gson = new Gson();
        if (cache_result != null && !cache_result.equals("")) {
            BibiliNvgDomain cache_domain = gson.fromJson(cache_result, BibiliNvgDomain.class);
            if (cache_domain.getFlag()) {
                if (cache_domain.getData() != null && cache_domain.getData().size() >= 3) {
                    List<ImageView> imageViews = new ArrayList<>();
                    for (int i = 0; i < 3; i++) {
                        final BibiliNvgDomain.Data dataBean = cache_domain.getData().get(i);
                        ImageView iv = new ImageView(mActivity);
                        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        imageViews.add(iv);
                        Glide.with(mActivity)
                                .load("" + dataBean.getImg())
                                .asBitmap()
                                .placeholder(getResources().getColor(R.color.default_lightgray))
                                .animate(R.anim.fade_in)
                                .into(iv);
                        iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("merchandiseId", dataBean.getId());
                                Tools.redirectActivity(mActivity, GeneicStoreInfoActivity.class, map);
                            }
                        });

                    }
                    indexMainImgviewpager.setAdapter(new ImgBannerViewpagerAdpater(imageViews));
                    indexMainImgviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                            for (int i = 0; i < imgs_dot.length; i++) {
                                View iv = rootView.findViewById(imgs_dot[i]);
                                if (iv != null) {
                                    if (i == position) {
                                        iv.setAlpha(1.0f);
                                    } else {
                                        iv.setAlpha(0.4f);
                                    }
                                }
                            }
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                    indexMainImgviewpager.setCurrentItem(0, true);
                    indexMainImgviewpager.setDirection(AutoScrollViewPager.RIGHT);
                    indexMainImgviewpager.setInterval(3000);
                    indexMainImgviewpager.setAutoScrollDurationFactor(10);
                    indexMainImgviewpager.startAutoScroll(3000);


                }
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("location", "2");
        Xutils.GET(HttpUrl.getBilling, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                BibiliNvgDomain cache_domain = gson.fromJson(result, BibiliNvgDomain.class);
                if (cache_domain.getFlag()) {
                    if (cache_domain.getData() != null && cache_domain.getData().size() >= 3) {
                        Tools.setCache(mActivity, HttpUrl.getBilling + "location:1", result);
                        List<ImageView> imageViews = new ArrayList<>();
                        for (int i = 0; i < 3; i++) {
                            final BibiliNvgDomain.Data dataBean = cache_domain.getData().get(i);
                            ImageView iv = new ImageView(mActivity);
                            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            imageViews.add(iv);
                            Glide.with(mActivity)
                                    .load("" + dataBean.getImg())
                                    .asBitmap()
                                    .placeholder(getResources().getColor(R.color.default_lightgray))
                                    .animate(R.anim.fade_in)
                                    .into(iv);
                            iv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("merchandiseId", dataBean.getId());
                                    Tools.redirectActivity(mActivity, GeneicStoreInfoActivity.class, map);
                                }
                            });

                        }
                        indexMainImgviewpager.setAdapter(new ImgBannerViewpagerAdpater(imageViews));
                        indexMainImgviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                            @Override
                            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                            }

                            @Override
                            public void onPageSelected(int position) {
                                for (int i = 0; i < imgs_dot.length; i++) {
                                    View iv = rootView.findViewById(imgs_dot[i]);
                                    if (iv != null) {
                                        if (i == position) {
                                            iv.setAlpha(1.0f);
                                        } else {
                                            iv.setAlpha(0.4f);
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onPageScrollStateChanged(int state) {

                            }
                        });
                        indexMainImgviewpager.setCurrentItem(0, true);
                        indexMainImgviewpager.setDirection(AutoScrollViewPager.RIGHT);
                        indexMainImgviewpager.setInterval(3000);
                        indexMainImgviewpager.setAutoScrollDurationFactor(10);
                        indexMainImgviewpager.startAutoScroll(3000);
                    }


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null) {
            Toast.makeText(mActivity.getApplicationContext(), "定位失败", Toast.LENGTH_SHORT).show();
            city.setText("无法定位");
            return;
        }
        city.setText("" + aMapLocation.getCity() + aMapLocation.getDistrict());
    }


    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption;
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setLocationCacheEnable(true);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(false);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否强制刷新WIFI，默认为true，强制刷新。
        mLocationOption.setWifiScan(true);
        mLocationOption.setInterval(1000);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        return mLocationOption;
    }


    private class ImgBannerViewpagerAdpater extends PagerAdapter {
        List<ImageView> imageViews;

        ImgBannerViewpagerAdpater(List<ImageView> imageViews) {
            this.imageViews = imageViews;
        }

        @Override
        public int getCount() {
            return imageViews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView iv = imageViews.get(position);
            container.addView(iv);
            return iv;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //super.destroyItem(container, position, object);
            ImageView iv = imageViews.get(position);
            container.removeView(iv);
        }
    }

    public void onStart() {
        super.onStart();
//        if (this.storenoticeheadMv != null) {
//            this.storenoticeheadMv.startFlipping();
//        }
    }

    public void onStop() {
        super.onStop();
//        if (this.storenoticeheadMv != null) {
//            this.storenoticeheadMv.stopFlipping();
//        }
    }

    //送宝秒抢
    public void initHot() {
        final Map<String, String> map = new HashMap<>();
        map.put("pageSize", "10");
        map.put("page", ""+pagenow);
        Xutils.GET(HttpUrl.getHot, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                Gson gson = new Gson();
                final StoreDomain domain = gson.fromJson(result, StoreDomain.class);
                if (domain.getFlag()) {
                    if (domain.getData() != null && domain.getData().size() != 0) {
                        MarqueeFactory marqueeFactory = new NoticeMF(mActivity);
                        List<String> ara = new ArrayList<>();
                        for (int i = 0; i < domain.getData().size(); i++) {
                            StoreDomain.Data storeDomain = domain.getData().get(i);
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("merchandiseId", storeDomain.getId());
                                jsonObject.put("data", storeDomain.getName());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            ara.add(jsonObject.toString());
                        }
                        marqueeFactory.resetData(ara);
                        marqueeFactory.setOnItemClickListener(new MarqueeFactory.OnItemClickListener() {
                            @Override
                            public void onItemClickListener(MarqueeFactory.ViewHolder holder) {
                                StoreDomain.Data dataBean = domain.getData().get(holder.position);
                                Map<String, Object> map = new HashMap<>();
                                map.put("merchandiseId", dataBean.getId());
                                Tools.redirectActivity(mActivity, GeneicStoreInfoActivity.class, map);
                            }
                        });
                        storenoticeheadMv.setMarqueeFactory(marqueeFactory);


                        if (adater == null) {
                            storeRecycler.setAdapter(adater = new MerRecylcerAdaper(domain.getData(), mActivity));
                        } else {
                            adater.initRefresh(domain.getData());
                        }
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //送宝秒抢
    public void appendHot() {
        isloading=true;
        final Map<String, String> map = new HashMap<>();
        map.put("pageSize", "10");
        map.put("page", pagenow+"");
        Xutils.GET(HttpUrl.getHot, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                isloading=false;
                Gson gson = new Gson();
                final StoreDomain domain = gson.fromJson(result, StoreDomain.class);
                if (domain.getFlag()) {
                    if (domain.getData() != null && domain.getData().size() != 0) {
                        if (adater == null) {
                            storeRecycler.setAdapter(adater = new MerRecylcerAdaper(domain.getData(), mActivity));
                        } else {
                            adater.initAppend(domain.getData());
                        }
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                isloading=false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public class NoticeMF extends MarqueeFactory<TextView, String> {
        private LayoutInflater inflater;

        public NoticeMF(Context mContext) {
            super(mContext);
            inflater = LayoutInflater.from(mContext);
        }

        @Override
        public TextView generateMarqueeItemView(String data) {
            TextView mView = (TextView) inflater.inflate(R.layout.notice_item, null);

            String datas = null;
            int merchandiseId = 0;
            try {
                JSONObject jsonObject = new JSONObject(data);
                datas = jsonObject.getString("data");
                merchandiseId = jsonObject.getInt("merchandiseId");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mView.setText(datas);
            final int finalMerchandiseId = merchandiseId;

            return mView;

        }
    }


    public class MerRecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<StoreDomain.Data> dataBeen;
        public LayoutInflater inflater;

        public MerRecylcerAdaper(List<StoreDomain.Data> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_generic_store_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final StoreDomain.Data dataBean = dataBeen.get(position);
            ih.shopping_title_user.setText("" + dataBean.getName());
            ih.shopping_info_user.setText("");
            Glide.with(mActivity)
                    .load("" + dataBean.getImg())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .override(500, 500)
                    .into(ih.icon);
            ih.now_tv.setText("¥" + dataBean.getPrice());
            ih.origin_tv.setText("¥" + dataBean.getOriginalPrice());

            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("merchandiseId", dataBean.getId());
                    Tools.redirectActivity(mActivity, GeneicStoreInfoActivity.class, map);
                }
            });


        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public ImageView icon;
            public TextView origin_tv;
            public TextView shopping_title_user;
            public TextView shopping_info_user;
            public TextView now_tv;
            public TextView song_tv;
            public TextView xiandao_tv;
            public CornerLabelView labelview;

            public IndexHoler(View itemView) {
                super(itemView);
                song_tv = itemView.findViewById(R.id.song_tv);
                now_tv = itemView.findViewById(R.id.now_tv);
                xiandao_tv = itemView.findViewById(R.id.xiandao_tv);
                rootView = itemView;
                icon = itemView.findViewById(R.id.icon);
                origin_tv = itemView.findViewById(R.id.origin_tv);
                origin_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
                origin_tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线
                origin_tv.getPaint().setAntiAlias(true);// 抗锯齿
                origin_tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰
                shopping_title_user = itemView.findViewById(R.id.shopping_title_user);
                shopping_info_user = itemView.findViewById(R.id.shopping_info_user);
                labelview = itemView.findViewById(R.id.labelview);
            }
        }

        public void deleteRow(int position) {
            dataBeen.remove(position);
            notifyDataSetChanged();
        }

        public void initRefresh(List<StoreDomain.Data> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<StoreDomain.Data> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }


    }


}
